package ferp.center.client;

import ferp.core.Version;
import ferp.core.game.Game;
import ferp.core.log.Log;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * User: igorgok
 * Date: 5/20/12 11:35 AM
 */
public class Action
{
  private static final String PROFILE = "profile/";
  private static final String GAME    = "game/";
  private static final String BID     = "bid/";
  private static final String ENGAGEMENT = "engagement/";

  public static final String TAG = Log.TAG + "/C";

  public static final String PROFILE_CREATE    = PROFILE + "create";
  public static final String PROFILE_UPDATE    = PROFILE + "update";
  public static final String PROFILE_DELETE    = PROFILE + "delete";
  public static final String PROFILE_HACKED    = PROFILE + "hacked";
  public static final String GAME_RESULT_ADD   = GAME + "result/add";
  public static final String GAME_DELETE       = GAME + "delete";
  public static final String GAME_REPORT_ADD   = GAME + "report/send";
  public static final String GAME_REPORT_GET   = GAME + "report/get";
  public static final String LEADERBOARD_GET   = "leaderboard/get";
  public static final String CONFIG_GET        = "config/get";
  public static final String BID_ADD           = BID + "add";
  public static final String ENGAGEMENT_ACCEPT = ENGAGEMENT + "accept";
  public static final String ENGAGEMENT_CLEAR  = ENGAGEMENT + "clear";
  public static final String POLL_SUBMIT       = "poll/submit";
  public static final String TUTORIAL_START    = "tutorial/%d/start";
  public static final String TUTORIAL_END      = "tutorial/%d/end";

  public static <Input, Output> Output execute(String action, Input input, Class<Output> outputClass) throws IOException
  {
    final DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(Action.URL + action + "?v=" + Version.CURRENT);

    post.setEntity(new StringEntity(Game.gson.toJson(input), "UTF-8"));

/*  needed to work with local server

    if (BuildConfig.DEBUG)
    {
      post.setHeader("X-AppEngine-Country", "Israel");
      post.setHeader("X-AppEngine-Region", "North");
      post.setHeader("X-AppEngine-City", "Haifa");
    }
*/

    String output = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");

    Log.debug(TAG, output.length() > 100 ? output.substring(0, 100) : output);

    return outputClass == null ? null : Game.gson.fromJson(output, outputClass);
  }

  private static final String URL = "https://ferpcenter.appspot.com/";
  //private static final String URL = "http://igorgok-tp.haifa.ibm.com:8080/";
  //private static final String URL = "http://OLEGS-TP.haifa.ibm.com:8080/";
}
